package com.android.lovely.ui.viewmodel

import androidx.lifecycle.viewModelScope
import com.android.lovely.api.UnlockCardUseCase
import com.android.lovely.api.collectRobotUseCase
import com.android.lovely.api.fetchBotCardsListCase
import com.android.lovely.api.service.botService
import com.android.lovely.api.unlockAllCardUserCase
import com.android.lovely.const.CardUL
import com.android.lovely.data.CardDetailBean
import com.android.lovely.framework.BaseViewModel
import com.android.lovely.framework.doContinuousOperation
import com.android.lovely.framework.launchWithLoading
import com.android.lovely.room.BotCacheService
import com.android.lovely.user.UserManager
import com.kotlin.extensions.bus.FlowBus
import com.kotlin.extensions.bus.post
import com.kotlin.extensions.coroutine.CoroutineExt.launchSafety
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.SharedFlow

/**
 * @author why
 * @date 2025/3/12 14:57
 */
class DetailViewModel : BaseViewModel() {

    // 当前页码
    var currentPage = 1
    // 机器人的唯一标识符
    var robotId = 0
    // 是否正在加载卡片
    private var isCardLoadingInProgress = false
    // 创建者的唯一标识符
    private var creatorUniqueId: Int = 0
    var hasMore = true


    // 用于发射卡片详情信息的可变共享流
    private val _cardDetailFlow = MutableSharedFlow<CardDetailBean>(extraBufferCapacity = 1)
    // 对外暴露的不可变共享流，用于观察卡片详情信息
    val cardDetailFlow: SharedFlow<CardDetailBean> get() = _cardDetailFlow

    // 当前的卡片详情信息
    var currentCardDetail: CardDetailBean? = null

    // 设置机器人的唯一标识符
    fun setRobotUniqueId(id: Int) {
        this.robotId = id
    }

    // 加载卡片信息
    fun loadCardInfo() {
        if (isCardLoadingInProgress || BotCacheService.isBotLoading(robotId)) {
            return
        }
        isCardLoadingInProgress = true
        viewModelScope.launchSafety {
            doContinuousOperation {
                val result = fetchBotCardsListCase(robotId, currentPage, 10)
                val cardList = result.cardList
                if(cardList.isEmpty() || cardList.size < 10) {
                    hasMore = false
                    BotCacheService.updateBot(robotId) {
                        if(cardList.isNotEmpty()) {
                            if (currentPage == 1) {
                                this.cards = cardList
                            } else {
                                this.cards = this.cards.toMutableList().apply { addAll(cardList) }
                            }
                        }
                    }
                }else {
                    if (currentPage == 1) {
                        cardList.takeIf { it.isNotEmpty() }?.let {
                            BotCacheService.updateBot(robotId) {
                                this.cards = it
                            }
                        }
                    } else {
                        BotCacheService.updateBot(robotId) {
                            this.cards = this.cards.toMutableList().apply { addAll(cardList) }
                        }
                        currentPage++
                    }
                }
            }
            isCardLoadingInProgress = false
        }
    }

    // 解锁所有卡片
    fun unlockAllCards() {
        viewModelScope.launchWithLoading {
            val response = unlockAllCardUserCase(robotId)
            val remainingGem = response.getOrDefault("surplus", UserManager.userInfo?.point ?: 0)
            UserManager.updateGems(remainingGem)
            BotCacheService.updateBot(robotId) {
                cards.forEach { it.isUnlock = true }
                FlowBus.post(
                    CardUL(cards.map { it.id })
                )
            }
        }
    }

    // 解锁单个卡片
    fun unlockSingleCard(cardId: Int) {
        viewModelScope.launchWithLoading {
            UnlockCardUseCase.execute(robotId, cardId)
        }
    }

    // 收藏机器人
    fun collectTheRobot() {
        viewModelScope.launchSafety {
            collectRobotUseCase(robotId)
        }
    }

    // 获取卡片详情信息
    fun obtainCardDetail() {
        viewModelScope.launchSafety {
            currentCardDetail = botService.getRoleCardInfo(mapOf("bot_id" to robotId)).apply {
                _cardDetailFlow.emit(this)
            }
        }
    }
}